<template>
	<div class='app-container'>
		<div class="roleManage">
			<div class="mainLeft">
				<div class="btnList">
					<el-button @click="addRole()" size="medium" type="primary">新 增</el-button>
					<el-button @click="reviseRole()"  size="medium" type="primary">修 改</el-button>
					<el-button @click="delectRole()" size="medium" type="primary">删 除</el-button>
				</div>
				<div class="tableList">
					<div>
						<div class="title">角色名</div>
						<li @click="chooseItem(item)" :class="{choosed:item.choosed}" v-for='(item, index) of roleList' :key='index'>
							<a href="javascript:;">{{item.roleName}}</a>
						</li>
					</div>
				</div>
			</div>
			<div class="mainRight">
				<div class="titleRight">
					<span>权限列表分配</span>
					<span><el-button type="primary" @click="saveNodes()">保存</el-button></span>
				</div>
				<div class="checkBox">
					<el-tree
						:data="checkList"
						show-checkbox
						node-key="id"
						ref="tree"
						highlight-current
						:props="listRules"
						:default-expanded-keys="defaultList"
						:default-checked-keys='choosedArray'
						>
					</el-tree>
				</div>
			</div>
				<template name="角色添加">
					<el-dialog center title="角色添加" :visible.sync="showAddRole">
					<div class="layerForm">
							<el-form  ref="addForm" :rules="addRules" :label-position="'left'" label-width="100px" :model="formLabelAlign">
								<el-form-item prop="name" label="角色名称：">
									<el-input  v-model="formLabelAlign.name"></el-input>
								</el-form-item>
								<el-form-item  prop="code" label="角色秘钥：">
									<el-input   v-model="formLabelAlign.code"></el-input>
								</el-form-item>
							
							</el-form>
						</div>
						<div slot="footer" class="dialog-footer">
							<el-button class='approl' type="primary" @click="submitClick('1')">取 消</el-button>
							<el-button class="refuse" @click="submitClick('2')">完 成</el-button>
						</div>
					</el-dialog>
			</template>
		</div>
  </div>
</template>
<script>
import {roleList, addRole, delectRole, getRoleInfo, getSystemMenu, bindRole } from '@/api/systemManage'
import { validatAlphabets } from '@/utils/validate'


export default {
  data() {
    	const validCode = (rule, value, callback) => {
            if (!validatAlphabets(value)) {
                callback(new Error('仅只能输入大小写字母'))
            } else {
                callback()
            }
        }
	  
		return{
			roleList:[],
			show:false,
			checkList: [],
			formLabelAlign:{name:'',code:'', id:''},
			showAddRole:false,
			addRules:{
				code: [{ required: true, trigger: 'blur', validator: validCode }],
				name:
				[{ required: true, message: '请输角色名称', trigger: 'blur' },
				{ min: 3,  message: '长度不小于 3 个字符', trigger: 'blur' }]
			},
			choosedRole:[],
			listRules:{label:'menuName',value:'id',children:'children'},
			choosedArray:[],
			defaultList:['9a6f82ee45ec4082b9d16a6db343f89b','3344684d5e80460485a27712acb5f682','62cf3ad240ce4544a07d90467dc3043d']
			}
	},
	methods:{
		getRoleList() {
			roleList().then(res=>{
				console.log('ssss')
				var data = res.data.data
				for(var item of data){
					this.$set(item,'choosed',false)
				}
				this.roleList = data
			})
		},
		getSystemMenu() {
			const data = {}
			getSystemMenu(data).then(res=> {
				console.log('caidanxs')
				console.log(res)
				this.checkList = res.data.data
			})
		},
		chooseItem(item) {
			for(var select of this.roleList){
				select.choosed = false
			}
			item.choosed = true
			this.choosedRole = item
			this.getRoleInfo(item)
		},
		getRoleInfo(item) {
			const {id} = item
			getRoleInfo(id).then(res=> {
				this.getChoosedList(res.data.data)
			})
		},
		getChoosedList(list) {
			console.log(list)
			this.choosedArray = []
			for(var item of list){
				if(this.defaultList.indexOf(item.id) === -1){
					this.choosedArray.push(item.id)
				}else {
					console.log('item')
				}
			}
			this.$refs.tree.setCheckedKeys(this.choosedArray)
		},
		saveNodes() {
			if(this.choosedRole != ''){
				const loading = this.$loading({
					lock: true,
					text: 'Loading',
					spinner: 'el-icon-loading',
					background: 'rgba(0, 0, 0, 0.7)'
				});
				let list = this.$refs.tree.getCheckedNodes()
				let arr = []
				for(let item of list){
					arr.push(item.id)
					if(item.pid && item.pid !== 'ROOT'){
						arr.push(item.pid)
					}
					if(item.children != null){
						for(let secItem of item.children){
							arr.push(secItem.id)
							arr.push(secItem.pid)
							if(secItem.children != null) {
									for(let thirItem of secItem.children) {
										arr.push(thirItem.id)
										arr.push(thirItem.pid)
									}
								}
						}
					}
				}
				arr.push('9a6f82ee45ec4082b9d16a6db343f89b')    //逻辑中会存在第一层没放进去的可能
				const paramsArray = Array.from(new Set(arr)); //去重
				console.log(paramsArray)
				const data={
					"menuIds":paramsArray,
					roleId:this.choosedRole.id
				}	
				bindRole(data).then(res=>{
					console.log(res)
					if(res.data.code === 0){
						loading.close()
						this.$message.success('保存成功')
					}else {
						loading.close()
						this.$message.error('保存异常')
					}
				})			
			}else {
				this.$message.warning('请选择一条角色名')
			}
			

			
		},
		

		addRole() {
			this.showAddRole = true
		},
		delectRole() {
			if(this.choosedRole != ''){
				const {id} = this.choosedRole
				 this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                    }).then(() => {
                        delectRole(id).then(res=> {
                            if(res.data.code === 0){
                                this.$message.success('删除成功')
                                this.getRoleList()
                            }else{
                                this.$message.error('删除失败')
                            }
                        })
                    }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });          
                    });			
			}else {
				this.$message.warning('请选择要修改的角色名')
			}
		},
		reviseRole() {
			if(this.choosedRole != ''){
				this.showAddRole = true
				const {roleCode , roleName, id} = this.choosedRole
				this.formLabelAlign = {
					code:roleCode,
					name:roleName,
					id:id
				}				
			}else {
				this.$message.warning('请选择要修改的角色名')
			}
		},
		submitClick(code){
			if(code === '1'){
				this.showAddRole = false
			}else{
				console.log(this.$refs.addForm)
				 this.$refs.addForm.validate(valid => {
					if(valid) {
						const data = {
							id:this.formLabelAlign.code == '' ? '' : this.formLabelAlign.code,
							roleCode:this.formLabelAlign.code,
							roleName:this.formLabelAlign.name
						}
					addRole(data).then(res=>{
						if(res.data.code === 0) {
							this.showAddRole=false
							this.$message.success('添加成功')
							this.getRoleList()
						}else{
							this.showAddRole = false
							this.$message('操作异常')
						}
					})
					 }
				 })
			}
		}
	},
	
	created() {
		this.getRoleList()
		this.getSystemMenu()
	}
}
</script>
<style rel="stylesheet/scss" lang="scss">
   @import "src/styles/mixin.scss";
	 .roleManage{
		background-color: #FFF; 
		height: 100%;
		display: flex;
		flex-direction: row;
		.mainLeft{
			width:40%;
			padding: 0 15px;
			border-right: 2px solid #e4e4e4;
			padding-bottom: 500px;
			.btnList{
				padding: 15px 0;
				display: flex;
				justify-content: flex-end;
				border-bottom: 2px solid #e4e4e4;
				.el-button{
					margin-left: 20px;
				}
			}
			.tableList{
				font-size: 14px;
				border: 1px solid #e4e4e4;
				border-bottom: none;
				margin-top: 15px;
				.title{
					padding: 10px 0 10px 15px;
					border-bottom: 1px solid #e4e4e4;
				}
				 li{
					list-style: none;
					border-bottom: 1px solid #e4e4e4;
					padding: 10px 0;
					text-align:center;

				}
				.choosed{
					background-color: #27BAAD !important;
					color: #FFF !important;
				}
			}
		}
		.mainRight{
			width: 60%;
			padding: 0 15px;
			.titleRight{
				display: flex;
				flex-direction: row;
				justify-content: space-between;
				height: 66px;
				align-items: center;
				border-bottom: 2px solid #e4e4e4;
				span{
					display: inline-block;
				}
			}
			.checkBox{
				margin-top: 15px;
			}
		}
			.el-dialog{
				width:30% !important;
			}
	 }



</style>


